import React, { useRef, useState } from 'react';

import { DeleteOutlined, PlusOutlined, ReloadOutlined, SettingOutlined } from '@ant-design/icons';

import {
  type DeviceGroup,
  deviceGroupListApi,
  deviceGroupDeleteApi,
  deviceGroupSaveApi,
} from '@/api/deviceGroupApi';
import type { OperationType } from '@/constants';
import { OperationTypeList } from '@/constants';
import { useRouter } from '@/hooks/useRouter';
import { TableLocalePresets } from '@/utils/tableUtils';

import DeviceGroupAddForm from './modules/add';

import type { ActionType, ProColumns } from '@ant-design/pro-components';

/**
 * 设备分组管理页面组件
 * 提供设备分组的创建、编辑、删除等功能，支持批量操作
 */
const DeviceGroupManager = () => {
  // 路由导航
  const { navigate } = useRouter();

  // 表格操作引用
  const actionRef = useRef<ActionType>(null);

  // 表单实例
  const [form] = AForm.useForm();

  // 抽屉状态管理
  const [drawerShow, setDrawerShow] = useState(false);
  const [drawerType, setDrawerType] = useState<OperationType>('ADD');
  const [currentRecord, setCurrentRecord] = useState<Partial<DeviceGroup>>({});

  // 表格选择状态
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  // 加载状态（预留用于后续功能）
  // const [loading, setLoading] = useState(false);

  /**
   * 获取设备分组列表数据
   * @param params 查询参数
   * @returns 格式化的表格数据
   */
  const fetchData = async (params: Record<string, unknown>) => {
    try {
      // setLoading(true); // 预留用于后续功能

      // 处理分页参数
      const requestParams = {
        ...params,
        pageNum: params.current,
        pageSize: params.pageSize,
      };

      const res = await deviceGroupListApi(requestParams);

      if (res.success) {
        const responseData = res.data;

        // 处理不同的响应数据结构
        if (Array.isArray(responseData)) {
          // 如果直接返回数组
          return {
            success: true,
            data: responseData,
            total: responseData.length,
          };
        } else if (responseData && typeof responseData === 'object') {
          // 如果返回对象结构
          const listData = responseData as API.ListType<DeviceGroup>;
          return {
            success: true,
            data: listData.records ?? [],
            total: listData.total ?? 0,
          };
        }

        return {
          success: true,
          data: [],
          total: 0,
        };
      } else {
        window.$message.error(res.message || '获取设备分组列表失败');
        return {
          success: false,
          data: [],
          total: 0,
        };
      }
    } catch (error) {
      console.error('获取设备分组列表失败:', error);
      window.$message.error('获取设备分组列表失败，请稍后重试');
      return {
        success: false,
        data: [],
        total: 0,
      };
    } finally {
      // setLoading(false); // 预留用于后续功能
    }
  };

  /**
   * 删除单个设备分组
   * @param record 设备分组记录
   */
  const handleDelete = async (record: DeviceGroup) => {
    // 参数验证
    if (!record || !record.id) {
      window.$message.error('删除失败：分组ID不存在');
      return;
    }

    const groupName = record.groupName || '未知分组';

    AModal.confirm({
      title: '确认删除',
      content: `确定要删除设备分组${groupName}吗？删除后不可恢复。请先确保分组下没有设备`,
      okText: '确定删除',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          const res = await deviceGroupDeleteApi({ ids: [record.id] });
          if (res.success) {
            window.$message.success('设备分组删除成功');
            actionRef.current?.reload();

            // 如果删除的分组在选中列表中，需要更新选中状态
            if (record.id && selectedRowKeys.includes(record.id)) {
              const newSelectedKeys = selectedRowKeys.filter(key => key !== record.id);
              setSelectedRowKeys(newSelectedKeys);
            }
          } else {
            window.$message.error(res.message || '删除失败');
          }
        } catch (error) {
          console.error('删除设备分组失败:', error);
          window.$message.error('删除失败，请重试');
        }
      },
    });
  };

  /**
   * 批量删除设备分组
   */
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      window.$message.warning('请先选择要删除的设备分组');
      return;
    }

    // 获取有效的分组ID
    const validIds = selectedRowKeys.map(key => Number(key)).filter(id => !isNaN(id) && id > 0);

    if (validIds.length === 0) {
      window.$message.error('选中的分组ID无效');
      return;
    }

    AModal.confirm({
      title: '确认批量删除',
      content: `确定要删除选中的${validIds.length}个设备分组吗？删除后不可恢复。请先确保分组下没有设备`,
      okText: '确定删除',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          const res = await deviceGroupDeleteApi({ ids: validIds });
          if (res.success) {
            window.$message.success(`成功删除 ${validIds.length} 个设备分组`);
            // 清空选中状态
            setSelectedRowKeys([]);
            // 刷新列表
            actionRef.current?.reload();
          } else {
            window.$message.error(res.message || '批量删除失败');
          }
        } catch (error) {
          console.error('批量删除设备分组失败:', error);
          window.$message.error('批量删除失败，请重试');
        }
      },
    });
  };

  /**
   * 打开新增设备分组抽屉
   */
  const handleAdd = () => {
    setDrawerType('ADD');
    setCurrentRecord({});
    form.resetFields();
    setDrawerShow(true);
  };

  /**
   * 打开编辑设备分组抽屉
   * @param record 设备分组记录
   */
  const handleEdit = (record: DeviceGroup) => {
    if (!record || !record.id) {
      window.$message.error('分组ID不存在，无法编辑');
      return;
    }

    setDrawerType('EDIT');
    setCurrentRecord(record);
    setDrawerShow(true);

    // 预填充表单数据
    setTimeout(() => {
      form.setFieldsValue(record);
    }, 100);
  };

  /**
   * 保存设备分组
   * 支持新增和编辑两种模式
   */
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const requestParams = {
        ...currentRecord,
        ...values,
      };

      const res = await deviceGroupSaveApi(requestParams);
      if (res.success) {
        const successMessage = drawerType === 'ADD' ? '设备分组创建成功' : '设备分组更新成功';
        window.$message.success(successMessage);

        // 延迟关闭抽屉，确保用户看到成功提示
        setTimeout(() => {
          form.resetFields();
          handleDrawerClose();
          actionRef.current?.reload();
        }, 300);
      } else {
        window.$message.error(res.message || '保存失败');
      }
    } catch (error) {
      console.error('保存设备分组失败:', error);
      if (error instanceof Error) {
        window.$message.error(`保存失败：${error.message}`);
      } else {
        window.$message.error('保存失败，请重试');
      }
    }
  };

  /**
   * 关闭抽屉并重置状态
   */
  const handleDrawerClose = () => {
    setCurrentRecord({});
    setDrawerType('ADD');
    setDrawerShow(false);
    form.resetFields();
  };

  /**
   * 表格列配置
   */
  const columns: ProColumns<DeviceGroup>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      search: false,
    },
    {
      title: '分组名称',
      dataIndex: 'groupName',
      key: 'groupName',
      // width: 120,
      ellipsis: true,
      search: true,
    },
    {
      title: '描述',
      dataIndex: 'remark',
      key: 'remark',
      width: 200,
      ellipsis: true,
      search: false,
      render: (_, record) => record.remark || <span style={{ color: '#999' }}>暂无描述</span>,
    },
    {
      title: '设备数量',
      dataIndex: 'deviceCount',
      key: 'deviceCount',
      width: 120,
      search: false,
      render: (_, record) => {
        const count = record.deviceCount || 0;
        return (
          <span style={{ color: count > 0 ? '#1890ff' : '#999', fontWeight: 'bold' }}>
            {count} 台
          </span>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      search: false,
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      fixed: 'right',
      search: false,
      render: (_, record) => (
        <ASpace size="small">
          <AButton
            type="link"
            size="small"
            onClick={() => {
              if (!record.id) {
                window.$message.error('分组ID不存在，无法查看详情');
                return;
              }
              navigate(`/device/group/detail/${record.id}`);
            }}
          >
            查看
          </AButton>
          <AButton type="link" size="small" onClick={() => handleEdit(record)}>
            编辑
          </AButton>
          <AButton type="link" size="small" danger onClick={() => handleDelete(record)}>
            删除
          </AButton>
        </ASpace>
      ),
    },
  ];

  return (
    <div className="page-wrapper">
      <ADrawer
        destroyOnHidden
        title={`设备分组${OperationTypeList[drawerType].label}`}
        width={600}
        closable={{ 'aria-label': 'Close Button' }}
        footer={
          <ARow justify="end">
            <ASpace>
              <AButton
                onClick={() => {
                  setDrawerShow(false);
                }}
              >
                返回
              </AButton>
              {drawerType != 'DETAIL' && (
                <AButton type="primary" onClick={handleSubmit}>
                  提交
                </AButton>
              )}
            </ASpace>
          </ARow>
        }
        onClose={handleDrawerClose}
        open={drawerShow}
      >
        <div className="w-full px-8 py-8">
          <AForm form={form} layout="vertical" labelAlign="right" labelCol={{ span: 12 }}>
            <React.Suspense fallback={<ASpin />}>
              <DeviceGroupAddForm
                form={form}
                data={currentRecord as DeviceGroup}
                mode={drawerType === 'EDIT' ? 'edit' : 'add'}
              />
            </React.Suspense>
          </AForm>
        </div>
      </ADrawer>

      <div className="page-title">
        <div className="page-main-title">设备分组管理</div>
        <div className="page-sub-title">
          分组管理提供了对设备场景化的管理方式，通过分组可以实现设备批量监测和联动
        </div>
      </div>

      <div className="page-content-box">
        <div className="page-content flex show-bg">
          <div className="w-full">
            <PProTable<DeviceGroup>
              className="mh-table"
              actionRef={actionRef}
              columns={columns}
              request={fetchData}
              rowKey="id"
              search={{
                span: 6,
                labelWidth: 'auto',
                defaultCollapsed: false,
              }}
              pagination={{
                defaultPageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) =>
                  `共 ${total} 项数据，当前显示第 ${range[0]}-${range[1]} 项`,
              }}
              scroll={{ x: 1000 }}
              size="small"
              options={{
                density: false,
                reloadIcon: (
                  <AButton icon={<ReloadOutlined />} key="reload">
                    刷新
                  </AButton>
                ),
                setting: {
                  draggable: true,
                  checkable: true,
                  showListItemOption: true,
                  settingIcon: <AButton icon={<SettingOutlined />}>设置</AButton>,
                  listsHeight: 400,
                },
              }}
              toolBarRender={() => [
                <AButton key="add" icon={<PlusOutlined />} type="primary" onClick={handleAdd}>
                  新增分组
                </AButton>,
                <AButton
                  key="batch-delete"
                  icon={<DeleteOutlined />}
                  danger
                  onClick={handleBatchDelete}
                  disabled={selectedRowKeys.length === 0}
                >
                  批量删除{selectedRowKeys.length > 0 ? `(${selectedRowKeys.length})` : ''}
                </AButton>,
              ]}
              locale={TableLocalePresets.product(actionRef)}
              tableAlertRender={false} // 隐藏"已选择 X 项"提示
              tableAlertOptionRender={false} // 隐藏"取消选择"等操作按钮
              rowSelection={{
                selectedRowKeys,
                onChange: keys => {
                  setSelectedRowKeys(keys);
                },
                getCheckboxProps: record => ({
                  disabled: false,
                  name: record.groupName,
                }),
                // 隐藏选择操作按钮
                selections: false,
              }}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default DeviceGroupManager;
